const express = require('express');
const router = express.Router();
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

// 获取用户今日统计
router.get('/today', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const today = new Date().toISOString().split('T')[0];
    
    // 获取今日统计数据
    const stats = await query(
      `SELECT * FROM user_statistics 
       WHERE user_id = ? AND stat_date = ?`,
      [userId, today]
    );
    
    // 获取用户总积分
    const user = await query(
      'SELECT total_points FROM users WHERE id = ?',
      [userId]
    );
    
    // 获取连续学习天数
    const streak = await query(
      `SELECT COUNT(*) as streak_days FROM user_statistics 
       WHERE user_id = ? AND focus_sessions > 0 
       ORDER BY stat_date DESC`,
      [userId]
    );
    
    // 获取本周统计
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - weekStart.getDay());
    const weekStartStr = weekStart.toISOString().split('T')[0];
    
    const weekStats = await query(
      `SELECT 
         SUM(focus_sessions) as week_focus_sessions,
         SUM(focus_duration) as week_focus_duration,
         SUM(tasks_completed) as week_tasks_completed,
         SUM(points_earned) as week_points_earned
       FROM user_statistics 
       WHERE user_id = ? AND stat_date >= ?`,
      [userId, weekStartStr]
    );
    
    // 获取本月统计
    const monthStart = new Date();
    monthStart.setDate(1);
    const monthStartStr = monthStart.toISOString().split('T')[0];
    
    const monthStats = await query(
      `SELECT 
         SUM(focus_sessions) as month_focus_sessions,
         SUM(focus_duration) as month_focus_duration,
         SUM(tasks_completed) as month_tasks_completed,
         SUM(points_earned) as month_points_earned
       FROM user_statistics 
       WHERE user_id = ? AND stat_date >= ?`,
      [userId, monthStartStr]
    );
    
    res.json({
      success: true,
      data: {
        today: stats[0] || {
          focus_sessions: 0,
          focus_duration: 0,
          tasks_completed: 0,
          points_earned: 0,
          work_sessions: 0,
          break_sessions: 0
        },
        total_points: user[0]?.total_points || 0,
        streak_days: streak[0]?.streak_days || 0,
        week: weekStats[0] || {
          week_focus_sessions: 0,
          week_focus_duration: 0,
          week_tasks_completed: 0,
          week_points_earned: 0
        },
        month: monthStats[0] || {
          month_focus_sessions: 0,
          month_focus_duration: 0,
          month_tasks_completed: 0,
          month_points_earned: 0
        }
      }
    });
  } catch (error) {
    console.error('获取今日统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取今日统计失败'
    });
  }
});

// 获取用户历史统计
router.get('/history', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { days = 30 } = req.query;
    
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));
    const startDateStr = startDate.toISOString().split('T')[0];
    
    const history = await query(
      `SELECT 
         stat_date,
         focus_sessions,
         focus_duration,
         tasks_completed,
         points_earned,
         work_sessions,
         break_sessions
       FROM user_statistics 
       WHERE user_id = ? AND stat_date >= ?
       ORDER BY stat_date DESC`,
      [userId, startDateStr]
    );
    
    res.json({
      success: true,
      data: history
    });
  } catch (error) {
    console.error('获取历史统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取历史统计失败'
    });
  }
});

// 获取用户成就
router.get('/achievements', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const achievements = await query(
      `SELECT 
         ua.*,
         a.achievement_name,
         a.achievement_description,
         a.points_reward
       FROM user_achievements ua
       LEFT JOIN (
         SELECT 'first_focus' as achievement_type, '初次专注' as achievement_name, '完成第一次专注会话' as achievement_description, 50 as points_reward
         UNION ALL SELECT 'focus_streak_3', '专注达人', '连续3天完成专注会话', 100
         UNION ALL SELECT 'focus_streak_7', '专注大师', '连续7天完成专注会话', 300
         UNION ALL SELECT 'focus_streak_30', '专注传奇', '连续30天完成专注会话', 1000
         UNION ALL SELECT 'total_focus_10', '专注新手', '累计完成10次专注会话', 200
         UNION ALL SELECT 'total_focus_50', '专注专家', '累计完成50次专注会话', 500
         UNION ALL SELECT 'total_focus_100', '专注宗师', '累计完成100次专注会话', 1000
       ) a ON ua.achievement_type = a.achievement_type
       WHERE ua.user_id = ?
       ORDER BY ua.unlocked_at DESC`,
      [userId]
    );
    
    res.json({
      success: true,
      data: achievements
    });
  } catch (error) {
    console.error('获取用户成就失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户成就失败'
    });
  }
});

// 获取用户学习目标
router.get('/goals', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { type = 'all' } = req.query;
    
    let whereClause = 'WHERE user_id = ?';
    let params = [userId];
    
    if (type !== 'all') {
      whereClause += ' AND goal_type = ?';
      params.push(type);
    }
    
    const goals = await query(
      `SELECT * FROM user_goals 
       ${whereClause}
       ORDER BY created_at DESC`,
      params
    );
    
    res.json({
      success: true,
      data: goals
    });
  } catch (error) {
    console.error('获取学习目标失败:', error);
    res.status(500).json({
      success: false,
      message: '获取学习目标失败'
    });
  }
});

// 获取用户学习习惯
router.get('/habits', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const habits = await query(
      `SELECT 
         h.*,
         COUNT(r.id) as total_records,
         COUNT(CASE WHEN r.completed = 1 THEN 1 END) as completed_records,
         MAX(r.record_date) as last_record_date
       FROM user_habits h
       LEFT JOIN user_habit_records r ON h.id = r.habit_id
       WHERE h.user_id = ? AND h.is_active = 1
       GROUP BY h.id
       ORDER BY h.created_at DESC`,
      [userId]
    );
    
    res.json({
      success: true,
      data: habits
    });
  } catch (error) {
    console.error('获取学习习惯失败:', error);
    res.status(500).json({
      success: false,
      message: '获取学习习惯失败'
    });
  }
});

// 更新统计数据
router.post('/update', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { 
      type, 
      value = 1, 
      duration = 0,
      points = 0 
    } = req.body;
    
    const today = new Date().toISOString().split('T')[0];
    
    // 检查今日统计记录是否存在
    const existing = await query(
      'SELECT * FROM user_statistics WHERE user_id = ? AND stat_date = ?',
      [userId, today]
    );
    
    if (existing.length === 0) {
      // 创建今日统计记录
      await query(
        `INSERT INTO user_statistics 
         (user_id, stat_date, focus_sessions, focus_duration, tasks_completed, points_earned, work_sessions, break_sessions) 
         VALUES (?, ?, 0, 0, 0, 0, 0, 0)`,
        [userId, today]
      );
    }
    
    // 根据类型更新统计
    let updateFields = [];
    let updateValues = [];
    let shouldAddPoints = false;
    let pointsToAdd = 0;
    
    switch (type) {
      case 'focus_session':
        updateFields.push('focus_sessions = focus_sessions + ?');
        updateValues.push(value);
        updateFields.push('focus_duration = focus_duration + ?');
        updateValues.push(duration);
        updateFields.push('work_sessions = work_sessions + ?');
        updateValues.push(value);
        
        // 检查每日积分获取次数限制（5次）
        if (points > 0) {
          // 获取用户当前积分获取次数和日期
          const userStats = await query(
            'SELECT daily_points_count, last_points_date FROM users WHERE id = ?',
            [userId]
          );
          
          const user = userStats[0];
          const lastPointsDate = user?.last_points_date;
          const currentCount = user?.daily_points_count || 0;
          const maxDailyCount = 5;
          const pointsPerSession = 10;
          
          // 检查是否是新的日期，如果是则重置计数
          let shouldReset = false;
          if (!lastPointsDate || lastPointsDate !== today) {
            shouldReset = true;
          }
          
          // 检查是否已达到每日限制
          if (shouldReset || currentCount < maxDailyCount) {
            updateFields.push('points_earned = points_earned + ?');
            updateValues.push(pointsPerSession);
            shouldAddPoints = true;
            pointsToAdd = pointsPerSession;
          }
        }
        break;
      case 'break_session':
        updateFields.push('break_sessions = break_sessions + ?');
        updateValues.push(value);
        break;
      case 'task_completed':
        updateFields.push('tasks_completed = tasks_completed + ?');
        updateValues.push(value);
        break;
      case 'points_earned':
        // 检查每日专注次数限制（5次）
        const currentStats = await query(
          'SELECT focus_sessions FROM user_statistics WHERE user_id = ? AND stat_date = ?',
          [userId, today]
        );
        
        const currentSessions = currentStats[0]?.focus_sessions || 0;
        const maxDailySessions = 5;
        const pointsPerSession = 10;
        
        if (currentSessions < maxDailySessions) {
          updateFields.push('points_earned = points_earned + ?');
          updateValues.push(pointsPerSession);
          shouldAddPoints = true;
          pointsToAdd = pointsPerSession;
        }
        break;
    }
    
    if (updateFields.length > 0) {
      updateValues.push(userId, today);
      await query(
        `UPDATE user_statistics SET ${updateFields.join(', ')} WHERE user_id = ? AND stat_date = ?`,
        updateValues
      );
    }
    
    // 更新用户总积分和积分获取次数（仅在应该添加积分时）
    if (shouldAddPoints && pointsToAdd > 0) {
      // 获取用户当前积分获取次数
      const userStats = await query(
        'SELECT daily_points_count, last_points_date FROM users WHERE id = ?',
        [userId]
      );
      
      const user = userStats[0];
      const lastPointsDate = user?.last_points_date;
      const currentCount = user?.daily_points_count || 0;
      
      // 如果是新日期，重置计数；否则增加计数
      let newCount = 1;
      if (lastPointsDate && lastPointsDate === today) {
        newCount = currentCount + 1;
      }
      
      await query(
        'UPDATE users SET total_points = total_points + ?, daily_points_count = ?, last_points_date = ? WHERE id = ?',
        [pointsToAdd, newCount, today, userId]
      );
    }
    
    res.json({
      success: true,
      message: '统计数据更新成功'
    });
  } catch (error) {
    console.error('更新统计数据失败:', error);
    res.status(500).json({
      success: false,
      message: '更新统计数据失败'
    });
  }
});

module.exports = router;
